/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.chigs.web.doku.revision;

import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.string.StringValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import brix.web.nodepage.BrixPageParameters;

import com.googlecode.chigs.domain.Module;
import com.googlecode.chigs.domain.Product;
import com.googlecode.chigs.domain.Revision;
import com.googlecode.chigs.repository.ChigsFacade;
import com.googlecode.chigs.web.ChigsWebSession;
import com.googlecode.chigs.web.common.RevisionByModuleDataProvider;
import com.googlecode.chigscommons.repository.GenericDomainService;
import com.googlecode.chigscommons.web.common.ActionPanelBuilder;
import com.googlecode.chigscommons.web.common.ViewActionLink;
import com.googlecode.chigscommons.web.common.table.AjaxFallbackDefaultDataTableBuilder;

/**
 * 
 * @author Ingo Renner
 * @author Henning Teek
 *
 */
@AuthorizeInstantiation("ROLE_USER")
public class ManageRevisionsPanel extends Panel {
	private static final Logger log = LoggerFactory.getLogger(ManageRevisionsPanel.class);
	
	@SpringBean
	private ChigsFacade chigs;

	@SpringBean
	private GenericDomainService genericDomainService;
	
    private Product product;
    private Module module;

	public ManageRevisionsPanel(String id) {
		super(id);
		
		StringValue productIdparam = BrixPageParameters.getCurrent().getQueryParam("product");
		Long productId = !productIdparam.isEmpty() ? productIdparam.toLongObject() : null;

		StringValue moduleIdParam = BrixPageParameters.getCurrent().getQueryParam("module");
		Long moduleId = !moduleIdParam.isEmpty() ? moduleIdParam.toLongObject() : null;

		this.product = productId != null ? genericDomainService.load(Product.class, productId) : ((ChigsWebSession) ChigsWebSession.get()).getUserSettings().getProduct();
		this.module = moduleId != null ? genericDomainService.load(Module.class, moduleId) : null;

		add(getComponentTable());
		add(getProductSelector());
		add(getModuleSelector());		
	}

	private DropDownChoice<Product> getProductSelector() {
		List<Product> products = genericDomainService.loadAll(Product.class);
		if (products.size() == 1){ // Selection nicht nötig
			ManageRevisionsPanel.this.product = products.get(0);
			ManageRevisionsPanel.this.addOrReplace(getComponentTable());
		}
		DropDownChoice<Product> dropDownChoice = new DropDownChoice<Product>("product",
				new PropertyModel<Product>(this, "product"),
				products,
				new ChoiceRenderer<Product>("name", "id")){
			@Override
			protected void onSelectionChanged(Product prod) {
				log.info("changing product from " + prod + " to " + ManageRevisionsPanel.this.product);
				ManageRevisionsPanel.this.product = prod;
				ManageRevisionsPanel.this.module = null;
				ManageRevisionsPanel.this.addOrReplace(getModuleSelector());
				ManageRevisionsPanel.this.addOrReplace(getComponentTable());
			}
			@Override
			protected boolean wantOnSelectionChangedNotifications() {
				return true;
			}
		};
		dropDownChoice.setNullValid(true);
		return dropDownChoice;
	}

	private DropDownChoice<Module> getModuleSelector() {
		List<Module> modules = chigs.loadModulesByProduct(product);
		if (modules.size() == 1){ // Selection nicht nötig
			ManageRevisionsPanel.this.module = modules.get(0);
			ManageRevisionsPanel.this.addOrReplace(getComponentTable());
		}
		DropDownChoice<Module> dropDownChoice = new DropDownChoice<Module>("module",
				new PropertyModel<Module>(this, "module"),
				modules,
				new ChoiceRenderer<Module>("name", "id")) {
			@Override
			protected void onSelectionChanged(Module mod) {
				log.info("changing module from " + mod + " to " + ManageRevisionsPanel.this.module);
				ManageRevisionsPanel.this.module = mod;
				ManageRevisionsPanel.this.addOrReplace(getComponentTable());
			}
			@Override
			protected boolean wantOnSelectionChangedNotifications() {
				return true;
			}
		};
		dropDownChoice.setNullValid(true);
		return dropDownChoice;
	}

	private Component getComponentTable() {
		final String id = "table";
		if (module == null || module.isNew()) {
			return new Label(id, "").setVisible(false);
		}
		return AjaxFallbackDefaultDataTableBuilder.getBuilder(ManageRevisionsPanel.this)
		.addDataProvider(new RevisionByModuleDataProvider(new Revision(), module))
		.add(new AbstractColumn<Object>(new StringResourceModel("actions.label", ManageRevisionsPanel.this, null)) {
			@Override
			public void populateItem(Item cellItem, String componentId, IModel rowModel) {
				final ActionPanelBuilder linkBuilder = ActionPanelBuilder.getBuilder();
				final Revision revision = (Revision) rowModel.getObject();
				// Eintrag anzeigen
				linkBuilder.add(new ViewActionLink(false) {
					@Override
					public void onClick(AjaxRequestTarget target) {
						EditOrCreateRevisionPanel view = new EditOrCreateRevisionPanel(ManageRevisionsPanel.this.getId(), product, module, revision);
						view.setOutputMarkupId(true);
						ManageRevisionsPanel.this.getParent().addOrReplace(view);
					}
				});
				cellItem.add(linkBuilder.build(componentId));
			}
		})				
		.addPropertyColumn("id", true)
		.addPropertyColumn("description", true)
		.addPropertyColumn("nr", true)
		.addPropertyColumn("user.email", true)
		.addPropertyColumn("version.version", true)
		.setNumberOfRows(10)
		.build(id);
	}
}
